/*
 *  Copyright 2013 Utkin Dmitry
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */


#include <QDebug>
#include <QHostAddress>
#include <QCoreApplication>
#include <google/protobuf/service.h>
#include <google/protobuf/descriptor.h>
#include <protoqtrpc/RpcController.h>
#include <protoqtrpc/SocketRpcChannel.h>
#include <protoqtrpc/BlockingClosure.h>
#include "protoqtrpc/test/TestService.pb.h"

#define TEST(expr, msg)\
    if (!(expr)) { qWarning() << __FILE__ << ":" << __LINE__ << " TEST failed:" << msg; exit(1); }

int main(int argc, char** argv)
{
    QCoreApplication app(argc, argv);

    protoqtrpc::SocketRpcChannel channel(QHostAddress("127.0.0.1"), 33601);
    protoqtrpc::RpcController controller;
    protoqtrpc::BlockingClosure closure;

    protoqtrpc::test::TestService::Stub client(&channel);
    protoqtrpc::test::TestRequest request;
    protoqtrpc::test::TestResponse response;

    request.set_request("test");


    const std::string& desc =
            protoqtrpc::test::TestService::descriptor()->options().GetExtension(protoqtrpc::description);

    TEST(desc == "Test service", "description");

    // basic call test
    client.echo(&controller, &request, &response, &closure);
    closure.wait();

    TEST(!controller.Failed(), controller.ErrorText().c_str());
    TEST(response.response() == request.request(), "response != request");


    // test cancellation
    controller.Reset();
    closure.reset();
    client.cancellableEcho(&controller, &request, &response, &closure);
    controller.StartCancel();
    closure.wait();

    TEST(controller.Failed() && controller.ErrorText() == "CANCELLED",
         controller.ErrorText().c_str());


    // test timeout
    channel.setTimeout(1000);
    controller.Reset();
    closure.reset();
    client.cancellableEcho(&controller, &request, &response, &closure);
    closure.wait();

    TEST(controller.Failed() && controller.ErrorText() == "TIMEOUT",
         controller.ErrorText().c_str());


    qDebug() << "tests ok";

    return 0;
}
